package org.jiajie.designpatterndemo.chain.middleware;

/**
 * Base middleware class.
 *
 * @author jie
 */
public abstract class Middleware {
    private Middleware next;

    /**
     * Builds chains of middleware objects
     *
     * @param first 链的第一个元素
     * @param chain 链
     * @return  middleware object
     */
    public static Middleware link(Middleware first, Middleware... chain){
        Middleware head = first;
        for (Middleware nextInChain: chain) {
            head.next = nextInChain;
            head = nextInChain;
        }
        return first;
    }

    /**
     * Subclasses will implement this method with concrete checks.
     *
     * @param email email
     * @param password  pwd
     * @return boolean
     */
    public abstract boolean check(String email, String password);

    /**
     * Runs check on the next object in chain or ends traversing
     * if we're in last object in chain.
     *
     * @param email email
     * @param password  pwd
     * @return  boolean
     */
    protected boolean checkNext(String email, String password){
        if (next == null){
            return true;
        }
        return next.check(email, password);
    }
}
